package com.ming.springboot.controller;

import com.ming.springboot.mbg.model.Student;
import com.ming.springboot.mbg.model.StudentExample;
import com.ming.springboot.service.StudentService;
import com.ming.springboot.util.StudentDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by mqsi on 2022/5/18 19:33
 */
@RestController
@RequestMapping("student")
@Api(tags = "学生管理")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@ApiOperation("添加学生信息")
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	// TODO 经测试此注解不生效，且会有问题，不建议使用
//	@CachePut(value = "student", key = "#student.sno")
	public Object insert(Student student){
//		student.setSno(StudentDataUtil.getSno());
		student.setSname(StudentDataUtil.getSName());
		student.setAge(StudentDataUtil.getAge());
		student.setAddress(StudentDataUtil.getAddress());
		int insertCount = studentService.insert(student);
		return "成功插入1条数据！学号：" + student.getSno();
	}

	@ApiOperation("查询所有学生信息")
	@RequestMapping(value = "/listStu", method = RequestMethod.GET)
	public List<Student> listStu(){
		StudentExample studentExample = new StudentExample();
		return studentService.selectByExample(studentExample);
	}

	@ApiOperation("根据学号查询学生信息")
	@RequestMapping(value = "/findByPk/{sno}", method = RequestMethod.GET)
	@Cacheable(value = "student", key = "#sno")
	public Student findByPk(@PathVariable String sno){
		return studentService.findByPk(sno);
	}

	@ApiOperation("根据学号删除学生信息")
	@RequestMapping(value = "/delete/{sno}", method = RequestMethod.DELETE)
	@CacheEvict(value = "student", key = "#sno")
	public void delete(@PathVariable String sno){
		studentService.delete(sno);
	}

	@ApiOperation("删除所有学生信息")
	@RequestMapping(value = "/deleteAll", method = RequestMethod.DELETE)
	@CacheEvict(value = "student", allEntries = true)
	public void deleteAll(){
		studentService.deleteAll();
	}
}
